#!/usr/bin/python
#
# Copyright (c) 2009, Michael J. Wiacek Jr.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

import logging
import random
import urllib2

class Error(Exception):
  pass


class HttpError(Error):
  def __init__(self, code=None, headers=None, url=None, body=None):
    Error.__init__(self)
    self.code = code
    self.headers = headers
    self.url = url
    self.body = body
  

def MakeRequest(method, params, auth=None, use_ssl=True):
  headers = {'Content-Type': 'application/json',
             'User-Agent': 'PyZenfolio Library',
             'X-Zenfolio-User-Agent': 'PyZenfolio Library'}

  if auth is not None:
    headers['X-Zenfolio-Token'] = auth

  if use_ssl is False and auth is None:
    url = 'http://www.zenfolio.com/api/1.1/zfapi.asmx'
  else:
    url = 'https://www.zenfolio.com/api/1.1/zfapi.asmx'

  body = '{ "method": "%s", "params": %s' % (method, params)
  body += ', "id": %d }' % random.randint(1, 2**16 - 1)

  headers['Content-Length'] = len(body)

  try:
    req = urllib2.Request(url, body, headers)
    return urllib2.urlopen(urllib2.Request(url, body, headers))
  except urllib2.HTTPError, e:
    raise HttpError(code=e.code, headers=e.headers, url=e.url, body=e.read())
